//
//  MJTEmoticonToolBar.swift
//  swiftWeiBo
//
//  Created by MJT on 16/7/20.
//  Copyright © 2016年 MJT. All rights reserved.
//

import UIKit

//定义枚举
enum MJTEmoticonToolBarButtonType: Int {
    case Nomal = 1000
    case Emoji = 1001
    case lxh = 1002
}
class MJTEmoticonToolBar: UIStackView {
    //  记录上次选中按钮
    var lastSelectedButton: UIButton?
    // 定义选中toolbar按钮的闭包
    var selectedToolBarButtonClosure: ((type: MJTEmoticonToolBarButtonType) -> ())?

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //添加控件,设置约束
    private func setupUI() {
        axis = .Horizontal
        distribution = .FillEqually
        addChildButton("默认", imageName: "compose_emotion_table_left",type: .Nomal)
        addChildButton("Emoji", imageName: "compose_emotion_table_mid",type: .Emoji)
        addChildButton("浪小花", imageName: "compose_emotion_table_right",type: .lxh)
    }
    //添加子控件
    private func addChildButton(title: String, imageName: String,type: MJTEmoticonToolBarButtonType) {
        let button = UIButton()
        //添加点击事件
        button.addTarget(self, action: "EmojiAction:", forControlEvents: .TouchUpInside)
        button.tag = type.rawValue
        if type == .Nomal {
            button.selected = true
            lastSelectedButton = button
        }
        //设置字体及颜色
        button.setTitle(title, forState: .Normal)
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitleColor(UIColor.grayColor(), forState: .Selected)
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        //设置背景图片
        button.setBackgroundImage(UIImage(named: imageName + "_normal"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: imageName + "_selected"), forState: .Selected)
        //取消高亮
        button.adjustsImageWhenHighlighted = false
        addArrangedSubview(button)
    }
    @objc private func EmojiAction(button: UIButton) {
        if lastSelectedButton == button {
            return
        }
        lastSelectedButton?.selected = false
        button.selected = true
        lastSelectedButton = button
        let type = MJTEmoticonToolBarButtonType(rawValue: button.tag)!
        selectedToolBarButtonClosure?(type: type)
    }
    //根据传入的section判断选中哪个按钮
    func selectEmotionButtonWithSection(section: Int) {
        //如果tag是0,则取的不是按钮,是当前控件
//        let view = viewWithTag(section + 1000)
//        print(view)
        //根据tag判断是否是同一个按钮,如果是不需要再次选中
        if section + 1000 == lastSelectedButton?.tag {
            return
        }
        let button = viewWithTag(section + 1000) as! UIButton

        lastSelectedButton?.selected = false
        button.selected = true
        lastSelectedButton = button

    }

}
